package cn.lix.sc.rpc.pdf;

import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Image;
import com.itextpdf.text.pdf.*;

import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;

public class Test {

    public static void main(String[] args) throws IOException, DocumentException {
        String html = PDFHelper.getTemplateContent("071515133867.ftl", null);
        byte[] bytes = PDFHelper.html2Pdf(html);
        //查找位置
        List<float[]> postions = ItextPDFUtil.findKeywordPostions(bytes, "ACT_RU_JOB");

        // 第一次找到的位置
        float[] postion = postions.get(0);
        System.out.println("x:" + postion[1] + " y:" + postion[2]);

        //Modify file using PdfReader
        //Read file using PdfReader
        PdfReader pdfReader = new PdfReader(bytes);
        PdfStamper pdfStamper = new PdfStamper(pdfReader, new FileOutputStream("D:/test.pdf"));

        Image image = Image.getInstance("E:\\workspace\\java_pdf\\src\\main\\resources\\images\\69f70ad3-1cd7-4793-8c89-99dea0311a1b.001.png");
        //Fixed Positioning
//        image.scaleToFit(100, 50);
        image.scaleAbsolute(100, 100);
        //Scale to new height and new width of image
        image.setAbsolutePosition(postion[1], postion[2]);

        System.out.println("pages-1:" + pdfReader.getNumberOfPages());

        PdfContentByte content = pdfStamper.getUnderContent((int) postion[0]);
        content.addImage(image);

        // 第二次找到的位置
        postion = postions.get(1);
        //Fixed Positioning
//        image.scaleToFit(100, 50);
        image.scaleAbsolute(100, 100);
        //Scale to new height and new width of image
        image.setAbsolutePosition(postion[1], postion[2]);

        System.out.println("pages-2:" + pdfReader.getNumberOfPages());
        content = pdfStamper.getUnderContent((int) postion[0]);
        content.addImage(image);

//        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
//        byte[] pdf = content.toPdf(PdfWriter.getInstance(content.getPdfDocument(), outputStream));
        pdfStamper.close();
    }
}
